package com.lucian.ge.hatchdo.www.controller;

import io.swagger.annotations.*;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.lucian.ge.comman.model.ResultMap;

import javax.mail.internet.MimeMessage;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.NotEmpty;

/**
 * Created by Lucicol on 2019/6/12.
 */
@Api(value = "MailController", description = "官网邮件服务")
@RestController
@RequestMapping("/mail")
public class MailController {
    private final ResultMap resultMap;

    @Autowired
    private JavaMailSender mailSender;
    public MailController(ResultMap resultMap) {
        this.resultMap = resultMap;
    }

    /**
     * 官网joinUs邮箱
     */

    @ApiOperation(value="官网joinUs邮箱", notes="")

    @PostMapping("/joinus")
    @ResponseBody
    public ResultMap joinUs(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) @Valid MailInfo mailInfo, BindingResult result) {
        //      参数校验
        if (result.hasErrors()) {
            return resultMap.fail().code(401).message(result.getFieldError().getDefaultMessage());
        }
//        System.out.println(mailInfo.getName());
//        System.out.println(mailInfo.getPhoneNub());
        try {
            final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom("93977131@qq.com");
//            message.setTo("93977131@qq.com");
            message.setTo("mini_wx_c@hatchdo.com");
            message.setSubject("官网联系我们join us,姓名,电话");
            message.setText("姓名:"+ mailInfo.getName()+ "," + "电话:" + mailInfo.getPhoneNub());
            this.mailSender.send(mimeMessage);
            return resultMap.success().code(200).message("成功发送邮件");
        } catch (Exception ex) {
            ex.printStackTrace();
//            return "error";
            return resultMap.fail().code(401).message("发送邮件失败");
        }
    }
}

@ApiModel
class MailInfo {

    @ApiModelProperty(value = "手机号")
    @NotEmpty(message="手机号不能为空")
    @Pattern(regexp = "1[3|4|5|7|8][0-9]\\d{8}",message="手机号格式错误")
    private String phoneNub;

    @ApiModelProperty(value = "还款对象")
    @NotEmpty(message="姓名不能为空")
    @Length(max = 20, message = "姓名长度限制最多20字符")
    private String name;

    public String getPhoneNub() {
        return phoneNub;
    }

    public void setPhoneNub(String phoneNub) {
        this.phoneNub = phoneNub;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
